<?php

namespace App\Store\Controllers\Financial\Statements;


use App\Store\Models\Account\SiteStore;
use App\Store\Models\Financial\Statements\FinancialStatementsProfit;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Common\Services\CommonExcelExport;
use Maatwebsite\Excel\Facades\Excel;

use App\Store\Validate\Financial\Statements\Profit as ValidateFinancialStatementsProfit;
use App\Common\Services\Store\Common as StoreCommon;

class ProfitController extends Controller
{

    public function getsearchdata(Request $request)
    {
        $store_id = $request->store_id;
        if ($store_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $date_start = strtotime($request->date_start);
        $date_end = strtotime($request->date_end);
        if ($date_start <= 0 || $date_end < $date_start) {
            return response()->json(['code' => '001', 'msg' => '无效日期']);
        }
        $syear = date('Y', $date_start);
        $smonth = date('m', $date_start);
        $eyear = date('Y', $date_end);
        $emonth = date('m', $date_end);

        if ($syear != $eyear) {
            return response()->json(['code' => '001', 'msg' => '不可跨年查询']);
        }


        $searchdata = FinancialStatementsProfit::query()
            ->where([['cp_id', $cp_id], ['store_id', $store_id], ['is_del', 1], ['year', $syear], ['month', '>=', $smonth], ['month', '<=', $emonth]])
            ->get()
            ->toArray();

        $searchdatainfo = [];
        for ($i = 1; $i <= 32; $i++) {
            $searchdatainfo['data_key_' . $i] = array_sum(array_column($searchdata, 'data_key_' . $i));
        }


        if ($syear == date('Y')) {
            $maxmonth = date('m');
        } else {
            $maxmonth = 12;
        }


        $totallist = FinancialStatementsProfit::query()
            ->where([['cp_id', $cp_id], ['store_id', $store_id], ['year', $syear], ['is_del', 1], ['month', '<=', $maxmonth]])
            ->get()
            ->toArray();
        $totalinfo = [];
        for ($i = 1; $i <= 32; $i++) {
            $totalinfo['data_key_' . $i] = array_sum(array_column($totallist, 'data_key_' . $i));
        }

        if ($request->isexport == 1) {
            return $this->doexport($searchdatainfo, $totalinfo, $store_id, $request->date_start, $request->date_end);
        }


        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['searchdatainfo' => $searchdatainfo, 'totalinfo' => $totalinfo]]);
    }

    public function getinfo(Request $request)
    {
        $store_id = $request->store_id;
        if ($store_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }


        $date = strtotime($request->date);
        if ($date <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效日期']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $year = date('Y', $date);
        $month = date('m', $date);
        $info = FinancialStatementsProfit::where([['cp_id', $cp_id], ['store_id', $store_id]])->where(['year' => $year, 'is_del' => 1, 'month' => $month])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '未找到可编辑记录']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    public function saveinfo(Request $request)
    {
        $store_id = $request->store_id;
        if ($store_id <= 0) {
            return response()->json(['code' => '001', 'msg' => '请选择门店']);
        }

        $data_arr = ['year', 'month', 'remark'];
        for ($i = 1; $i <= 32; $i++) {
            $data_arr[] = 'data_key_' . $i;
        }


        $req_data = $request->only($data_arr);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $Validate = new ValidateFinancialStatementsProfit;
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $info = FinancialStatementsProfit::where([['cp_id', $cp_id], ['store_id', $store_id]])->where(['year' => $req_data['year'], 'is_del' => 1, 'month' => $req_data['month']])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data = $req_data;
        unset($data['year']);
        unset($data['month']);
        $data['update_at'] = time();
        FinancialStatementsProfit::where([['cp_id', $cp_id], ['store_id', $store_id]])->where(['year' => $req_data['year'], 'is_del' => 1, 'month' => $req_data['month']])->update($data);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function doexport($info, $totalinfo, $store_id, $date_start, $date_end)
    {
        $title_arr = [
            '1' => '一、营业收入',
            '2' => '减：营业成本',
            '3' => '税金及附加',
            '4' => '其中：消费税',
            '5' => '营业税',
            '6' => '城市维护建设费',
            '7' => '资源税',
            '8' => '土地增值税',
            '9' => '城镇土地使用税、房产税、车船税、印花税',
            '10' => '教育费附加、矿产资源补偿费、 排污费',
            '11' => '销售费用',
            '12' => '其中：商品维修费',
            '13' => '广告费和业务宣传费',
            '14' => '管理费用',
            '15' => '其中：开办费', '16' => '业务招待费',
            '17' => '研究费用',
            '18' => '财务费用',
            '19' => '其中：利息费用（收入以“-”号填列）',
            '20' => '加：投资收益（损失以“-”号填列）',
            '21' => '二、营业利润（亏损以“-”号填列）',
            '22' => '加：营业外收入',
            '23' => '其中：政府补助',
            '24' => '减：营业外支出', '25' => '其中：坏账损失',
            '26' => '无法收回的长期债券投资损失',
            '27' => '无法收回的长期股权投资损失',
            '28' => '自然灾害等不可抗力因素造成的损失',
            '29' => '税收滞纳金',
            '30' => '三、利润总额（亏损总额以“-”号填列）',
            '31' => '所得税费用',
            '32' => '四、净利润（净亏损以“-”号填列）'
        ];
        $datawith = [
            'A' => '50', 'B' => '8', 'C' => '30', 'D' => '30'
        ];
        //
        $exceldata = [];
        $store_name = SiteStore::where('id', '=', $store_id)->value('store_name');
        $row = [
            ['title' => '利润表'],
            ['title' => $store_name . ' ' . $date_start . ' - ' . $date_end],
            [
                'title' => '项目',
                'keyindex' => '行次',
                'money' => '本月金额',
                'totalmoney' => '本年累计金额',
            ]
        ];
        // if($info['data_key_3']==0){
        //     //4+5+6+7+8+9+10
        //     $info['data_key_3']=$info['data_key_4']+$info['data_key_5']+$info['data_key_6']+$info['data_key_7']+$info['data_key_8']+$info['data_key_9']+$info['data_key_10'];
        // }

        // if($info['data_key_21']==0){
        //     //1-2-3-11-14-18+20
        //     $info['data_key_21']=$info['data_key_1']-$info['data_key_2']-$info['data_key_3']-$info['data_key_11']-$info['data_key_14']-$info['data_key_18']+$info['data_key_20'];
        // }


        // //30=21+22-24
        // if($info['data_key_30']==0){
        //     $info['data_key_30']=$info['data_key_21']+$info['data_key_22']-$info['data_key_24'];
        // }

        // //32=30-31
        // if($info['data_key_32']==0){
        //     $info['data_key_32']=$info['data_key_30']-$info['data_key_31'];
        // }

        for ($i = 1; $i <= 32; $i++) {
            $exceldata[] = [
                'title' => $title_arr[$i],
                'keyindex' => $i,
                'money' => $info['data_key_' . $i] / 100,
                'totalmoney' => $totalinfo['data_key_' . $i] / 100,
            ];
        }
        $filename = '利润表信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
    }
}
